package com.lagou.framework.container;

import com.lagou.framework.common.Request;
import com.lagou.framework.common.Response;
import com.lagou.framework.config.XmlServerConfig;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author srh
 * @date 2020/04/03
 **/
public class Host {

    private static Host instance = new Host();

    public static Host getInstance() {
        return instance;
    }

    /**
     * host 主机名
     */
    private String hostName;
    /**
     * 应用根目录
     */
    private String appBase;
    /**
     * 多个站点
     */
    private Map<String, Context> contextList;

    public void init(XmlServerConfig.Host host) {
        this.hostName = host.getName();
        this.appBase = host.getAppBase();
        this.contextList = new HashMap<>();

        File webRoot = new File(this.appBase);
        if (webRoot.isDirectory()) {
            String[] contextList = webRoot.list();
            for (String contextRootPath : Objects.requireNonNull(contextList)) {
                File contextPath = new File(String.format("%s%s%s", this.appBase, File.separator, contextRootPath));
                if (contextPath.isDirectory()) {
                    Context context = new Context();
                    context.init(contextPath.getAbsolutePath());
                    String appName = contextPath.getAbsolutePath().substring(contextPath.getAbsolutePath().lastIndexOf("/"));
                    this.contextList.put(appName, context);
                }
            }
        }
    }

    public void doService(Request request, Response response) throws IOException {
        for (Map.Entry<String, Context> entry : contextList.entrySet()) {
            if (request.getUrl().contains(entry.getKey())) {
                entry.getValue().doService(request, response);
                return;
            }
        }
    }
}
